﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LDSP.BRL;
using BYFW.DAL;
using System.Data;

namespace LDSP.UI.Admin
{
    public partial class ChooseInvalidList : LDSP.BRL.BaseAdminPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    this.CheckQS();
                }
                if (this.RB())
                {
                    this.InitDataDynamicBefore();
                    if (!IsPostBack)
                    {
                        this.BindTree();
                        this.InitTreeNodeSelection();
                        this.InitData();
                        this.BindGrid();
                    }
                    this.InitDataDynamicAfter();
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        protected string TitleName = "法律法规";
        protected string ReferenceName = "发布文号";

        protected Catalog m_catalog = null;
        protected Codification m_codification = null;

        /// <summary>
        /// 源文档的类型
        /// </summary>
        protected DocType DocType
        {
            get { return (DocType)this.GetVSInt("DocType"); }
            set
            {
                this.SetVS("DocType", value);
            }
        }
        /// <summary>
        /// 栏目ID
        /// </summary>
        protected int LastID
        {
            get { return this.GetVSInt("LastID"); }
            set
            {
                this.SetVS("LastID", value);
                m_catalog = null;
            }
        }
        protected Catalog Catalog
        {
            get
            {
                if (m_catalog == null)
                {
                    m_catalog = new Catalog();
                    if (LastID != 0)
                    {
                        m_catalog.GetProperties(LastID);
                    }
                }
                return m_catalog;
            }
        }
        protected string OriginalIds
        {
            get { return this.GetVSString("OriginalIds"); }
            set
            {
                this.SetVS("OriginalIds", value);
            }
        }
        /// <summary>
        /// 源文档ID
        /// </summary>
        protected int OwnerID
        {
            get { return this.GetVSInt("OwnerID"); }
            set
            {
                this.SetVS("OwnerID", value);
                m_catalog = null;
            }
        }
        /// <summary>
        /// 源文档
        /// </summary>
        protected Codification Codification
        {
            get
            {
                if (m_codification == null)
                {
                    m_codification = new Codification();
                    if (OwnerID != 0)
                    {
                        m_codification.GetProperties(OwnerID);
                    }
                }
                return m_codification;
            }
        }
        protected void CheckQS()
        {
            OwnerID = this.GetInt(this.Request.QueryString["id"]);
            DocType = (DocType)this.GetInt(this.Request.QueryString["docType"]);
            if (Codification.ID == 0)
            {
                OwnerID = 0;
            }
            else
            {
                DocType = Codification.DocType;
            }
            PageID = this.Request.QueryString["PageID"];
        }

        /// <summary>
        /// 传入参数，设置过滤条件
        /// </summary>
        protected void SetSpecialPageInfo()
        {
            g_pageInfo.Direction = true;
            g_pageInfo.Sort = "name";
            g_pageInfo.PageSize = 10;
            g_pageInfo.PageIndex = this.grd_list.PageIndex;
        }
        protected bool RB()
        {
            bool res = true;
            if (!this.HaveCatalogPermission(Codification.CatalogID))
            {
                this.JSAlert(string.Format("您没有设定此{0}的权限!", DocType.ToString()), true);
                res = false;
            }
            if (!res)
            {
                this.JSCloseWindow();
            }
            return res;
        }
        protected void InitData()
        {
            //不缓存则清空页面信息
            if (!needCachePageInfo)
            {
                g_pageInfo.ClearPageInfo();
            }
            this.GetCondition();
            this.SetSpecialPageInfo();
            this.BindDDLIsValid();
            this.InitInvalidIDs();
        }
        protected void InitDataDynamicBefore()
        {
            if(DocType == BRL.DocType.标准)
            {
                this.TitleName = "标准";
                this.ReferenceName = "标准号";
            }
            this.grd_list.Columns[2].HeaderText = TitleName + "名称";
            this.grd_list.Columns[5].HeaderText = ReferenceName;
        }
        protected void InitDataDynamicAfter()
        {
            this.JSSetDateTimeReadOnly(this.txt_releaseStartDT.ClientID);
            this.JSSetDateTimeReadOnly(this.txt_releaseEndDT.ClientID);
            this.JSSetDateTimeReadOnly(this.txt_implementStartDT.ClientID);
            this.JSSetDateTimeReadOnly(this.txt_implementEndDT.ClientID);
        }
        protected void InitInvalidIDs()
        {
            this.OriginalIds = this.InvalidList(PageID);
        }
        protected void BindGrid()
        {
            this.grd_list.PageSize = g_pageInfo.PageSize;
            this.grd_list.PageIndex = g_pageInfo.PageIndex;
            if (LastID == 0 && !LoginAdmin.IsSuper)
            {
                this.grd_list.DataSource = BYFW.SFL.CommonOP.SortedTable(new Codification().GetRecordsBySystemUserID(LoginAdmin.ID, g_pageInfo.ConditionWhere), g_pageInfo.GetSortExpression());
            }
            else
            {
                this.grd_list.DataSource = BYFW.SFL.CommonOP.SortedTable(new Codification().GetRecords(g_pageInfo.ConditionWhere, true), g_pageInfo.GetSortExpression());
            } 

            this.grd_list.DataBind();

            this.ShowChecked();
        }
        protected void BindTree()
        {
            this.tre_obj.Nodes.Clear();

            TreeNode all = new TreeNode();
            all.Text = "所有";
            all.Value = "0";
            this.tre_obj.Nodes.Add(all);

            List<Catalog> rootCatalogs = new Catalog().GetListRootByDefault();
            for (int i = 0; i < rootCatalogs.Count; i++)
            {
                if (HaveCatalogPermission(rootCatalogs[i].ID))
                {
                    TreeNode nd = new TreeNode();
                    nd.Text = rootCatalogs[i].Name;
                    nd.Value = rootCatalogs[i].ID.ToString();
                    all.ChildNodes.Add(nd);
                    this.BindTreeAssis(nd, rootCatalogs[i].ID);
                }
            }
            all.CollapseAll();
        }
        protected void BindTreeAssis(TreeNode parent, int parentID)
        {
            List<Catalog> catalogs = new Catalog().GetListByParentID(parentID);
            for (int i = 0; i < catalogs.Count; i++)
            {
                if (HaveCatalogPermission(catalogs[i].ID))
                {
                    TreeNode nd = new TreeNode();
                    nd.Text = catalogs[i].Name;
                    nd.Value = catalogs[i].ID.ToString();
                    parent.ChildNodes.Add(nd);
                    this.BindTreeAssis(nd, catalogs[i].ID);
                }
            }
        }
        protected void InitTreeNodeSelection()
        {
            if (this.tre_obj.Nodes.Count > 0)
            {
                this.tre_obj.Nodes[0].Select();
                this.LastID = this.GetInt(this.tre_obj.SelectedValue);
            }
        }
        protected void BindDDLIsValid()
        {
            this.ddl_isValid.Items.Clear();
            this.ddl_isValid.Items.Add("--请选择--");
            this.ddl_isValid.Items.Add(new ListItem("无效", "0"));
            this.ddl_isValid.Items.Add(new ListItem("有效", "1"));
            try
            {
                this.ddl_isValid.SelectedIndex = 0;
            }
            catch { }
        }

        protected void GetCondition()
        {
            string cond = (LastID > 0) ? DefaultDB.GetSQLNormalCondition("catalogID", EDataType.Int, LastID.ToString(), "=", true) : "";
            cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("enterpriseID", EDataType.Int, "0", "=", true), true);
            cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("docType", EDataType.Int, ((int)DocType).ToString(), "=", true), true);
            if (this.txt_name.Text.Trim() != "")
            {
                cond = this.AppendConditionMulti(cond, this.txt_name.Text.Trim(), "name", "Organization", "ReferenceNumber");
            }
            if (this.ddl_isValid.SelectedIndex > 0)
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("isValid", EDataType.Bool, this.ddl_isValid.SelectedValue, "=", true), true);
            }
            if (this.txt_releaseStartDT.Text.Trim() != "")
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("releaseDT", EDataType.Date, this.txt_releaseStartDT.Text, ">=", true), true);
            }
            if (this.txt_releaseEndDT.Text.Trim() != "")
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("releaseDT", EDataType.Date, this.txt_releaseEndDT.Text, "<=", true), true);
            }
            if (this.txt_implementStartDT.Text.Trim() != "")
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("implementDT", EDataType.Date, this.txt_implementStartDT.Text, ">=", true), true);
            }
            if (this.txt_implementEndDT.Text.Trim() != "")
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("implementDT", EDataType.Date, this.txt_implementEndDT.Text, "<=", true), true);
            }
            g_pageInfo.Condition = cond;
        }

        protected void btn_search_Click(object sender, EventArgs e)
        {
            try
            {
                this.GetCondition();
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void btn_ok_Click(object sender, EventArgs e)
        {
            try
            {
                this.JSCloseWindow();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void btn_cancel_Click(object sender, EventArgs e)
        {
            try
            {
                this.InvalidList(PageID, this.OriginalIds);
                this.JSCloseWindow();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        protected void grd_list_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    Codification ett = new Codification();
                    ett.GetProperties(((DataRowView)e.Row.DataItem).Row);
                    if (ett.ID == Codification.ID)
                    {
                        e.Row.Enabled = false;
                    }
                    this.ShowSequenceNumber(e.Row, 1);
                    e.Row.Cells[3].Text = ett.Category.Name;
                    e.Row.Cells[6].Text = this.FormatDT(ett.ReleaseDT);
                    e.Row.Cells[7].Text = this.FormatDT(ett.ImplementDT);
                    e.Row.Cells[8].Text = this.FormatDT(ett.UploadDT);
                    e.Row.Cells[9].Text = ett.IsValid ? "是" : "否";
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                g_pageInfo.PageIndex = e.NewPageIndex;
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void grd_list_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                if (g_pageInfo.Sort == e.SortExpression)
                {
                    g_pageInfo.Direction = !g_pageInfo.Direction;
                }
                else
                {
                    g_pageInfo.Direction = true;
                }
                g_pageInfo.Sort = e.SortExpression;
                this.BindGrid();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
        protected void tre_obj_SelectedNodeChanged(object sender, EventArgs e)
        {
            LastID = this.GetInt(this.tre_obj.SelectedValue);
            this.GetCondition();
            this.BindGrid();
        }

        protected void chb_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox chb = (CheckBox)sender;
            GridViewRow gvr = (GridViewRow)(chb.Parent.Parent);
            this.SetSelectedIds(grd_list.DataKeys[gvr.RowIndex].Value.ToString(), chb.Checked);
            this.ShowChecked();
        }

        protected void SetSelectedIds(string id, bool add)
        {
            if (id == "" || id == "0" || id == OwnerID.ToString())
            {
                return;
            }
            List<string> ids = this.SplitStrS(this.InvalidList(PageID));
            if (add)
            {
                if (!ids.Contains(id))
                {
                    ids.Add(id);
                    this.InvalidList(PageID, this.CombineStrS(ids));
                }
            }
            else if(ids.Contains(id))
            {
                ids.Remove(id);
                this.InvalidList(PageID, this.CombineStrS(ids));
            }
        }
        protected void ShowChecked()
        {
            for (int i = 0; i < grd_list.Rows.Count; i++)
            {
                if (grd_list.Rows[i].RowType == DataControlRowType.DataRow)
                {
                    CheckBox chb = grd_list.Rows[i].FindControl("chb") as CheckBox;
                    if (chb != null)
                    {
                        List<string> ids = this.SplitStrS(this.InvalidList(PageID));
                        chb.Checked = ids.Contains(grd_list.DataKeys[i].Value.ToString());
                    }
                }
            }
            List<string> idList = this.SplitStrS(this.InvalidList(PageID));
            List<string> nameList = new List<string>();
            for (int i = 0; i < idList.Count; i++)
            {
                int tmpID = this.GetInt(idList[i]);
                Codification ett = new Codification();
                ett.GetProperties(tmpID);
                nameList.Add(ett.Name);
            }
            this.txt_invalidList.Text = this.CombineStrS(nameList);
        }
    }
}